<template>
<div class="evaluation-container">
    <!-- 筛选条件卡片 -->
    <el-card class="filter-card" shadow="hover">
      <div class="filter-group">
        <el-select 
          v-model="query.semester"
          placeholder="选择学期"
          class="filter-item"
          @change="initCourse"
          clearable
          size="medium"
        >
          <el-option 
            v-for="semester in availableSemesters" 
            :key="semester" 
            :value="semester"
            :label="semester"
          />
        </el-select>

        <el-select
        filterable
          v-model="query.subId"
          placeholder="选择课程"
          class="filter-item"
          @change="initClass"
          clearable
          size="medium"
        >
          <el-option
            v-for="(item, index) in courseList"
            :key="index"
            :label="item.courseName"
            :value="item.subId"
          />
        </el-select>

        <el-select
        filterable
          v-model="query.classId"
          placeholder="选择班级"
          class="filter-item"
          @change="fetchEvaluationData"
          clearable
          size="medium"
        >
          <el-option
            v-for="(item, index) in classList"
            :key="index"
            :label="item.className"
            :value="item.classId"
          />
        </el-select>
      </div>
    </el-card>
     <!-- 分析图表卡片 -->

    <el-card :body-style="{position: 'relative'}">
    <div v-loading="loading" element-loading-text="数据加载中...">
    <el-card class="chart-card" shadow="hover">
      <div slot="header" class="card-header">
        <i class="el-icon-trend-charts"></i>
        <span>课程评教趋势分析</span>
        <el-tag v-if="query.semester" type="info" size="mini">
          {{ query.semester }}
        </el-tag>

      </div>
      <div ref="chartContainer" class="chart-box"></div>
    </el-card>
    </div>
    </el-card>
  </div>
  </template>
  
  <script>
  import * as echarts from 'echarts'
  import { getCourse,getClass,getEvaluate } from '@/api/txyStudentEvaluation';
  import { getSemester1 } from '@/api/dashboard'
  
  export default {
    data() {
      return {
        loading: false,
        availableSemesters: [], // 改为从后端动态获取
        chartInstance: null,
        query:{
          semester:'',
          subId:'',
          classId:'',
        },
        classQuery:{
          semester:'',
          subId:"",
        },
        courseList:[],//课程列表
        classList:[],//选择的课程id
      }
    },
  
    mounted() {
      getSemester1().then(res=>{
        this.availableSemesters=res.data
      })
      this.initChart()
      window.addEventListener('resize', this.handleResize)
    },
  
    beforeDestroy() {
      window.removeEventListener('resize', this.handleResize)
      this.chartInstance?.dispose()
    },
    methods: {
      initChart() {
        this.chartInstance = echarts.init(this.$refs.chartContainer)
      },
  
      // 处理原始数据
      processData(rawData) {
        
        const courseDateMap = new Map()
        
        rawData.forEach(item => {
          const date = new Date(item.evaTime).toLocaleDateString()
          const courseKey = `${item.name}|${date}`
          
          if (!courseDateMap.has(courseKey)) {
            courseDateMap.set(courseKey, {
              name: item.name,
              date,
              total: 0,
              students: new Set()
            })
          }
          
          const record = courseDateMap.get(courseKey)
          record.total += item.evaScore
          record.students.add(`${item.studentId}_${item.subId}`)
        })
  
        return Array.from(courseDateMap.values())
          .map(record => ({
            label: `${record.name}\n${record.date}`, // 使用换行符分隔
            date: record.date,
            value: record.students.size > 0 
              ? (record.total / (record.students.size * 6)) * 6 // 转换为总分
              : 0
          }))
          .sort((a, b) => new Date(a.date) - new Date(b.date))
      },
  
  
          // 获取后端数据
      initCourse(semester){
          getCourse(semester).then(res=>{
            this.courseList=res.data;
          })
      },
      initClass(subId){      
        this.classQuery.subId=subId;
        this.classQuery.semester=this.query.semester;
        getClass(this.classQuery).then(res => {
          this.classList=res.data;
        })
      },
  
      // 获取评教数据
      async fetchEvaluationData() {
        try {
            this.loading = true
            getEvaluate(this.query).then(res=>{
            this.updateChart(this.processData(res.data))
          })
  
        } catch (error) {
          console.error('评教数据获取失败:', error)
        } finally {
          this.loading = false
        }
      },
  
      // 更新图表
      updateChart(chartData) {
        const option = {
          title: {
            text: '课程评教趋势变化',
            left: 'center',
            textStyle: {
              fontSize: 16,
              color: '#303133'
            }
          },          
          tooltip: {
            trigger: 'axis',
            backgroundColor: 'rgba(255,255,255,0.98)',
            borderWidth: 0,
            padding: 12,
            extraCssText: 'box-shadow: 0 4px 12px rgba(0,0,0,0.1);',
            formatter: params => {
              const data = params[0]
              return `
                <div style="font-size:14px;color:#606266">
                  <div style="font-weight:600;color:#409EFF;margin-bottom:8px">
                    ${data.name.replace('\n', ' · ')}
                  </div>
                  <div style="display:flex;align-items:center;padding:4px 0">
                    <span style="flex:1">综合评分</span>
                    <span style="font-weight:600;color:#409EFF">${data.value.toFixed(1)}分</span>
                  </div>
                </div>
              `
            }
          },
          xAxis: {
            type: 'category',
            data: chartData.map(d => d.label),
            axisLine: {
              lineStyle: {
                color: '#DCDFE6'
              }
            },
            axisLabel: {
              rotate: 30,
              fontSize: 12,
              color: '#606266',
              formatter: value => {
                const [course, date] = value.split('\n')
                return `{course|${course}}\n{date|${date}}`
              },
              rich: {
                course: {
                  fontSize: 12,
                  fontWeight: 500,
                  lineHeight: 18
                },
                date: {
                  fontSize: 10,
                  color: '#909399',
                  lineHeight: 18
                }
              }
            }
          },
          yAxis: {
            type: 'value',
            name: '综合评分',
            min: 0,
            max: 100,
            splitLine: {
              lineStyle: {
                type: 'dashed'
              }
            },
            axisLabel: {
              formatter: '{value} 分',
              color: '#909399'
            },
          },
          series: [{
            name: '评教分数',
            type: 'line',
            smooth: true,
            showSymbol: chartData.length < 10,
            symbolSize: 8,
            lineStyle: {
              width: 3,
              color: '#409EFF'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(64, 158, 255, 0.4)' },
                { offset: 1, color: 'rgba(64, 158, 255, 0.05)' }
              ])
            },
              data: chartData.map(d => ({
                value: d.value,
                name: d.label  // 确保每个数据点都有对应的标签名称
              }))
          }],
          grid: {
            left: '3%',
            right: '3%',
            bottom: '12%',
            containLabel: true
          },
          dataZoom: [{
            type: 'inside',
            start: 0,
            end: 100,
            fillerColor: 'rgba(64,158,255,0.1)',
            bottom: 30
          }],
          grid: {
            containLabel: true,
            left: '3%',
            right: '3%',
            bottom: '10%'
          }
        }
  
        this.chartInstance.setOption(option)
      },
  
      handleResize() {
        this.chartInstance?.resize()
      },
    }
  }
  </script>
  
  <style scoped>
.evaluation-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.filter-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.filter-group {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
  padding: 8px;
}

.filter-item {
  width: 260px;
  transition: all 0.3s;
}

.filter-item:hover ::v-deep .el-input__inner {
  border-color: #409EFF;
}

.chart-card {
  border-radius: 8px;
  overflow: hidden;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px 24px;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  border-bottom: 1px solid #ebeef5;
}

.card-header i {
  font-size: 20px;
  color: #409EFF;
}

.card-header span {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.chart-box {
  width: 100%;
  height: 500px;
  padding: 15px;
}

@media (max-width: 768px) {
  .filter-item {
    width: 100%;
  }
  
  .chart-box {
    height: 400px;
  }
  
  .card-header {
    padding: 12px;
  }
  
  .card-header i {
    font-size: 18px;
  }
}
</style>